#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 即将拥有人鱼线的yjw
   @Time: 2023/11/2 15:33
   @File: checkFile.py
   @desc:
"""
import os
import sys
import time
from configparser import ConfigParser
from datetime import datetime
from dingtalkchatbot.chatbot import DingtalkChatbot
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


exe_dir = os.path.dirname(sys.argv[0])
path = os.path.join(exe_dir, 'config.ini')
# path = f'{os.getcwd()}\config.ini'
print(f'读取配置文件：{path}')
config = ConfigParser()
config.read(path, encoding='utf-8')
filepath = config.get('check', 'filePath')
waittime = config.get('check', 'time')
enable = config.get('dingding', 'enable')
webhook = config.get('dingding', 'webhook')
secret = config.get('dingding', 'secret')
last_slash_index = filepath.rfind('\\')
fileDir = filepath[:last_slash_index]
fileName = filepath[last_slash_index + 1:]

class MyEventHandler(FileSystemEventHandler):
    '''
    重写文件变动事件
    '''
    def on_modified(self, event):
        if event.src_path.endswith(fileName):
            print(f"文档{fileName}发生变动！")
            if enable == '0':
                send_dingtalk_message(webhook, secret, '变动详情请打开文件查看', filepath)
            else:
                with open(event.src_path, 'r',encoding='utf-8') as file:
                    content = file.read()
                    send_dingtalk_message(webhook, secret, content, filepath)

def monitor_document(document_path):
    '''
    # 创建事件处理器和观察者
    定时监测文件变动情况
    '''
    print(f'{document_path}文件监控开始！')
    print(f'{waittime}秒检查一次！')
    event_handler = MyEventHandler()
    observer = Observer()
    observer.schedule(event_handler, document_path, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(int(waittime))  # 每10秒检测一次
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


def send_dingtalk_message(webhook,secret,content,path):
    '''
    # 发送钉钉消息
    '''
    dogBOSS = DingtalkChatbot(webhook, secret)
    # red_msg = '<font color="#FFA500">级别:警告</font>'
    now_time = datetime.now().strftime('%Y.%m.%d %H:%M:%S')
    dogBOSS.send_markdown(
        title=f'检测文件变动提醒',
        text=f'### **文件变动检测通知**\n'
             # f'**{red_msg}**\n\n'
             f'**文件内容:**  {content}\n\n'
             f'**发送时间:**  {now_time}\n\n'
             f'**日志地址:** {path} \n',
             # f'**制品地址:**[点击跳转]({url}) \n',
        is_at_all=False)


if __name__ == '__main__':
    monitor_document(fileDir)